/**
 * Indents the selected text. Currently only works for \t characters.
 * 
 * TODO: Still need to implement for spaces as well as \t tabs.
 */

package drtySyntaxEditor.actions;

import java.awt.event.ActionEvent;

import javax.swing.text.BadLocationException;

import drtySyntaxEditor.DrtySyntaxEditor;

@SuppressWarnings("serial")
public class ActionIndent extends DrtySyntaxEditorAction {
	
	public ActionIndent(DrtySyntaxEditor ed) {
		super(ed);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {		
		int [] range = ActionUtils.getSelectedLinesRange(this.editor);
		if (range.length == 2) {
			try {
				String lineSep = System.getProperty("line.separator");
				String linesTxt = this.editor.getText(range[0], range[1] - range[0]);
				String [] lines = linesTxt.split("\\r?\\n");
				int selStart = this.editor.getSelectionStart();
				int selEnd = this.editor.getSelectionEnd();
				
				StringBuffer sb = new StringBuffer();
				int lineCount = lines.length;
				
				for (int i=0; i<lineCount; i++) {
					sb.append("\t" + lines[i]);
					selEnd++;
					
					// If this is the first line, move the selStart one back.
					if (i == 0) {
						selStart++;
					}
					
					if (i != lineCount - 1) {
						sb.append(lineSep);
					}
				}
				
				this.editor.select(range[0], range[1]);
				this.editor.replaceSelection(sb.toString());
				
				// Place selection back to how it was
				this.editor.select(selStart, selEnd);
			}
			catch (BadLocationException ex) {
				ex.printStackTrace();
			}
		}
		else {
			System.err.println("Problem getting the selected line range");
		}			
	}
}
